﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DiracTCC.Business
{
    public class GraphDataProcessor
    {
        /// <summary>
        /// The data to be turn into histogram must be in property x.
        /// </summary>
        /// <param name="points"></param>
        /// <returns></returns>
        public static IEnumerable<GraphPoint> GetHistogram(IEnumerable<GraphPoint> points, int numberOfDivisions)
        {
            var histogram = new List<GraphPoint>();

            try
            {
                double maxValue = points.Max(x => x.x);

                for (int i = 1; i <= numberOfDivisions; i++)
                {
                    histogram.Add(new GraphPoint
                    {
                        x = i * maxValue / numberOfDivisions,
                        y = 0
                    });
                }

                foreach (var item in points)
                {
                    int position = (int)Math.Ceiling(item.x / (maxValue / numberOfDivisions));

                    if (position >= numberOfDivisions)
                    {
                        histogram[numberOfDivisions - 1].y++;
                    }
                    else
                    {
                        histogram[position].y++;
                    }
                }
            }
            catch (Exception)
            {
                histogram.Add(new GraphPoint
                {
                    x = 1,
                    y = 1
                });
            }

            return histogram;
        }
    }
}
